package pers.yurwisher.rubick.gateway.filters;

import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import pers.yurwisher.rubick.gateway.constants.AttributesConstant;

/**
 * @author yq
 * @date 2018/12/29 14:19
 * @description 网关过滤器
 * @since V1.0.0
 */
public abstract class AbstractGateWayFilter implements GlobalFilter, Ordered {

    /**
     * 过滤器是否忽略
     */
    protected boolean ignore(ServerWebExchange exchange){
        return exchange.getAttribute(AttributesConstant.IGNORE_GLOBAL_FILTER) != null
                || ignoreExpress(exchange);
    }

    /**
     * 忽略表达式,满足条件则忽略此过滤器
     * @param exchange 请求exchange
     * @return 是否忽略此过滤器
     */
    protected abstract boolean ignoreExpress(ServerWebExchange exchange);

    /**
     * 存属性到 exchange
     * @param exchange ex
     * @param key key
     * @param value 值
     */
    protected void putAttribute(ServerWebExchange exchange, String key, Object value){
        exchange.getAttributes().put(key,value);
    }

    /**
     * 获取head
     * @param exchange exchange
     * @param key key
     * @return head
     */
    protected String getFirstHead(ServerWebExchange exchange, String key){
       return exchange.getRequest().getHeaders().getFirst(key);
    }
}
